﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float moveSpeed = 2f;
    public int hp = 2;
    public int myScore = 100;
    public Sprite[] state;
    public SpriteRenderer ren;
    public GameObject score;
    public float minSpinForce, maxSpinForce;

    public AudioClip[] deathClips;
    public AudioSource enemyAS;

    private Rigidbody2D self;
    private Transform frontCheck;


    // Start is called before the first frame update
    void Start()
    {
        enemyAS = GetComponent<AudioSource>();
        ren = transform.Find("Body").GetComponent<SpriteRenderer>();
        //Debug.Log(ren);
        self = GetComponent<Rigidbody2D>();
        frontCheck = transform.Find("FrontCheck");
    }

    void FixedUpdate()
    {
        Collider2D[] cols = Physics2D.OverlapPointAll(frontCheck.position);
        foreach(Collider2D c in cols)
        {
            if (c.tag == "Wall") {
                Flip();
                break;
            }
        }
        self.velocity = new Vector2(Mathf.Sign(transform.localScale.x) * moveSpeed
                                                , self.velocity.y);

    }

    public void hurt(int damege = 1)
    {
        if (hp == 0) return;
        hp = Mathf.Max(hp - damege, 0);
        ren.sprite = state[hp];Debug.Log(ren);
        if(hp == 0)
        {
            enemyAS.PlayOneShot(deathClips[Random.Range(0, deathClips.Length)]);
            Instantiate(score, transform.position + Vector3.up * 1.5f, Quaternion.identity);
            GameObject.Find("Hero").GetComponent<Items>().score += myScore;

            Collider2D[] cols = GetComponents<Collider2D>();
            foreach(Collider2D c in cols) c.isTrigger = true;
   
            SpriteRenderer[] rens = GetComponentsInChildren<SpriteRenderer>();
            foreach (SpriteRenderer ren_t in rens)
            {
                ren_t.enabled = false;
                ren_t.sortingLayerName = "UI";
            }
            ren.enabled = true;
            GetComponent<Animator>().enabled = false;

            self.freezeRotation = false;
            self.AddTorque(Random.Range(minSpinForce, maxSpinForce));
            //Debug.Log(transform.localRotation);
        }
    }
    void Flip()
    {
        transform.localScale = new Vector3(transform.localScale.x * (-1), transform.localScale.y);
    }
}
